﻿#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Tools.Services.Captcha/CaptchaServiceImpl 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       CaptchaServiceImpl
* 创建时间：  2025/6/4 11:22:14
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using DotNetCore.CAP.Dashboard;
using DotNetCore.CAP;
using Microsoft.AspNetCore.Mvc;
using SSPivot.Admin.Core.Service.communal.Captcha.Dto;
using SSPivot.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SSPivot.AspNetCore.Services;
using static Lazy.SlideCaptcha.Core.ValidateResult;
using SSPivot.Common.Helpers;
using Lazy.SlideCaptcha.Core;
using Lazy.SlideCaptcha.Core.Validator;

namespace SSPivot.Tools.Services.Captcha
{
    /// <summary>
    /// 验证码
    /// </summary>
    public class CaptchaServiceImpl : ApplicationService, ICaptchaService
    {
        #region 接口注入
        private readonly ICaptcha Captcha;
        public ISlideCaptchaService SlideCaptchaService { get; set; }
        public ICapPublisher CapPublisher { get; set; }
        /// <summary>
        /// 属性注入
        /// </summary>
        /// <param name="captcha"></param>
        public CaptchaServiceImpl(ICaptcha captcha)
        {
            Captcha = captcha;
        }
        #endregion

        #region 服务
        /// <summary>
        /// 生成
        /// </summary>
        /// <param name="captchaId">验证码id</param>
        /// <returns></returns>
        public CaptchaData Generate(string captchaId = null)
        {
            return Captcha.Generate(captchaId);
        }
        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="captchaId">验证码Id</param>
        /// <param name="track">滑动轨迹</param>
        /// <returns></returns>
        public ValidateResult CheckAsync([FromQuery] string captchaId, SlideTrack track)
        {
            if (captchaId.IsNull() || track == null)
            {
                throw ServiceResult.Exception("请完成安全验证");
            }

            return SlideCaptchaService.Validate(captchaId, track, false);
        }
        /// <summary>
        /// 发送短信验证码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        public async Task<string> SendSmsCodeAsync(SendSmsCodeDto input)
        {
            if (input.Mobile.IsNull())
            {
                throw ServiceResult.Exception("请输入手机号");
            }

            if (input.CaptchaId.IsNull() || input.Track == null)
            {
                throw ServiceResult.Exception("请完成安全验证");
            }

            var validateResult = Captcha.Validate(input.CaptchaId, input.Track);
            if (validateResult.Result != ValidateResultType.Success)
            {
                throw ServiceResult.Exception($"安全{validateResult.Message}");
            }

            var codeId = input.CodeId.IsNull() ? Guid.NewGuid().ToString() : input.CodeId;
            var code = RandomHelper.GetRandomNumber(6);
            await Cache.SetAsync(GlobalConfigTool.CacheKeys.GetSmsCodeKey(input.Mobile, codeId), code, TimeSpan.FromMinutes(5));

            //发送短信验证码
            await CapPublisher.PublishAsync(GlobalConfigTool.SubscribeNames.SmsSendCode, new
            {
                input.Mobile,
                Text = code
            });

            return codeId;
        }

        /// <summary>
        /// 发送邮件验证码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<string> SendEmailCodeAsync(SendEmailCodeDto input)
        {
            if (input.Email.IsNull())
            {
                throw ServiceResult.Exception("请输入邮件地址");
            }

            if (input.CaptchaId.IsNull() || input.Track == null)
            {
                throw ServiceResult.Exception("请完成安全验证");
            }

            var validateResult = Captcha.Validate(input.CaptchaId, input.Track);
            if (validateResult.Result != ValidateResultType.Success)
            {
                throw ServiceResult.Exception($"安全{validateResult.Message}");
            }

            var codeId = input.CodeId.IsNull() ? Guid.NewGuid().ToString() : input.CodeId;
            var code = RandomHelper.GetRandomNumber(6);
            await Cache.SetAsync(GlobalConfigTool.CacheKeys.GetEmailCodeKey(input.Email, codeId), code, TimeSpan.FromMinutes(5));

            //发送邮箱验证码
            await CapPublisher.PublishAsync(GlobalConfigTool.SubscribeNames.EmailSendCode, new EmailSendCodeEventDto
            {
                ToEmail = new EmailSendCodeEventDto.Models.EmailModel
                {
                    Address = input.Email,
                },
                Code = code,
            });

            return codeId;
        }
        #endregion
    }
}
